package com.robotlab.easytranslate.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.robotlab.easytranslate.R;
import com.robotlab.easytranslate.activity.MainActivity;
import com.robotlab.easytranslate.dbase.Wordbook;
import com.robotlab.easytranslate.util.HttpUtil;
import com.robotlab.easytranslate.util.InputMethodUtils;
import com.robotlab.easytranslate.util.JinshanParseUtil;
import com.robotlab.easytranslate.util.NetWorkUtil;
import com.robotlab.easytranslate.util.StringUtil;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;
import static android.support.constraint.Constraints.TAG;
import static com.robotlab.easytranslate.util.JinshanParseUtil.parseJinshanChineseToEnglishXMLWithPull;


public class TranslateFragment extends Fragment {

    private final String TAG = "TranslateFragment";

    public static EditText input;
    public AutoCompleteTextView output;
    //public static AutoCompleteTextView input,output;
    private ImageButton IB_tran, IB_clean, IB_sound, IB_copy;
    private CheckBox cb_collcet;
    private static final String APP_ID = String.valueOf(R.string.baidu_appid);
    private static final String SECURITY_KEY = String.valueOf(R.string.baidu_key);
    private boolean isQuere = false;
    private String voiceUrl = null;
    private CardView cv_example, cv_result;
    private TextView tv_example;
    private String QuereText, MeanText, VoiceText, VoiceTextUrl;
    public static Boolean isCollect = false;
    public static String word = "";

    public static String getWord() {
        return word;
    }

    public static void setWord(String word) {
        TranslateFragment.word = word;
    }

    public ImageButton getIB_tran() {
        return IB_tran;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_translate, container, false);
        initView(view);

        getDataFromOutSide();
        return view;
    }

    private void getDataFromOutSide() {
        MainActivity mainActivity = (MainActivity) getActivity();
        String data = mainActivity.data;
        if (data != null) {
            if (!data.equals("")) {
                input.setText(data);
                IB_tran.performClick();
                data = "";
                mainActivity.data = null;
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (word != ""&&word!="--") {
            //Toast.makeText(getContext(),word,Toast.LENGTH_SHORT).show();
            input.setText(word);
            isCollect = true;
            IB_tran.performClick();
            word = "";
        } else if (word == "--") {
            input.setText("");
            word = "";
            QuereText = "";
            MeanText = "";
            VoiceText = "";
            VoiceTextUrl = "";
        }
        word = "";
        //InputMethodUtils.openSoftKeyboard(getContext(),input);
    }

    private void initView(View view) {
        input = view.findViewById(R.id.TV_input);
        InputMethodUtils.openSoftKeyboard(getContext(), input);
        output = view.findViewById(R.id.TV_output);
        IB_tran = view.findViewById(R.id.IB_tran);
        IB_clean = view.findViewById(R.id.IB_clean);
        IB_copy = view.findViewById(R.id.IB_copy);
        IB_sound = view.findViewById(R.id.IB_sound);
        cv_example = view.findViewById(R.id.cv_example);
        tv_example = view.findViewById(R.id.tv_example);
        cv_result = view.findViewById(R.id.cv_result);
        cb_collcet = view.findViewById(R.id.CB_collect);
        input.addTextChangedListener(new TextWatcher() {
            private String mTemp;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                isQuere = false;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mTemp = editable.toString();
                voiceUrl = null;
                IB_clean.setVisibility(mTemp.isEmpty() ? View.GONE : View.VISIBLE);
                if (mTemp.isEmpty()) {
                    output.setText("");
                    cv_example.setVisibility(View.GONE);
                    cv_result.setVisibility(View.GONE);
                    QuereText = "";
                    MeanText = "";
                    VoiceText = "";
                    VoiceTextUrl = "";
                    cb_collcet.setChecked(false);
                }
            }
        });
        IB_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearInputContent();
                output.setText("");
                isQuere = false;
                voiceUrl = null;
                InputMethodUtils.openSoftKeyboard(getContext(), input);
                cv_example.setVisibility(View.GONE);
                cv_result.setVisibility(View.GONE);
                QuereText = "";
                MeanText = "";
                VoiceText = "";
                VoiceTextUrl = "";
                cb_collcet.setChecked(false);
            }
        });
        IB_tran.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String text = input.getText().toString();
                if (text.equals(null) || text.equals("")) {
                    Toast.makeText(getContext(), "请输入要翻译的内容", Toast.LENGTH_SHORT).show();
                    InputMethodUtils.openSoftKeyboard(getContext(), input);
                } else {
                    final String content = StringUtil.toLowerCaseFirstOne(text);
                    InputMethodUtils.closeSoftKeyboard(input);
                    if (NetWorkUtil.isNetConnected(getContext())) {
                        try {
                            //金山查词网址，默认xml，使用中
                            final String urlxml = "http://dict-co.iciba.com/api/dictionary.php?w=" + content + "&key=9ED0664FFB08623D298EF8E174475567";
                            String url = "http://dict-co.iciba.com/api/dictionary.php?w=" + content + "&type=json&key=9ED0664FFB08623D298EF8E174475567";
                            //String url = "http://www.iciba.com/index.php?a=getWordMean&c=search&list=1%2C2%2C3%2C4%2C5%2C8%2C9%2C10%2C12%2C13%2C14%2C18%2C21%2C22%2C3003%2C3005&word=" +content;
                            if (isQuere == false) {
                                isQuere = true;
                                if (JinshanParseUtil.isEnglish(content)) {
                                    HttpUtil.sendOkHttpRequest(urlxml, new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            Toast.makeText(getContext(), "获取翻译数据失败！", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            final String result = response.body().string();
                                            Log.d("TranslateFragment", result);
                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    cv_result.setVisibility(View.VISIBLE);
                                                    JinshanParseUtil.parseJinshanEnglishToChineseXMLWithPull(result);
                                                    SharedPreferences pref = getActivity().getSharedPreferences("JinshanEnglishToChinese", MODE_PRIVATE);

                                                    String queryText = pref.getString("queryText", "空");
                                                    String voiceEnText = pref.getString("voiceEnText", "空");
                                                    String voiceEnUrlText = pref.getString("voiceEnUrlText", "空");
                                                    String voiceAmText = pref.getString("voiceAmText", "空");
                                                    String voiceAmUrlText = pref.getString("voiceAmUrlText", "空");
                                                    String meanText = pref.getString("meanText", "空");
                                                    String exampleText = pref.getString("exampleText", "空");
                                                    output.setText("");
                                                    if (!queryText.equals(content)) {
                                                        output.setText(content);
                                                        voiceUrl = null;
                                                    } else {
                                                        output.setText("");
                                                        voiceUrl = voiceAmUrlText;
                                                        output.append("英 " + voiceEnText + " 美 " + voiceAmText + "\n" + meanText);
                                                        if (!exampleText.equals(null) || !exampleText.equals("空")) {
                                                            cv_example.setVisibility(View.VISIBLE);
                                                            tv_example.setText(exampleText);

                                                        } else {
                                                            cv_example.setVisibility(View.GONE);
                                                        }
                                                        QuereText = queryText;
                                                        MeanText = meanText;
                                                        VoiceText = voiceAmText;
                                                        VoiceTextUrl = voiceUrl;
                                                        List<Wordbook> wordbooks = DataSupport.findAll(Wordbook.class);
                                                        for (Wordbook wordbook : wordbooks) {
                                                            if (QuereText.equals(wordbook.getQuereText())) {
                                                                isCollect = true;
                                                                cb_collcet.setChecked(true);
                                                            } else {
                                                                isCollect = false;
                                                            }
                                                        }
                                                    }

                                                }
                                            });
                                        }
                                    });
                                } else {
                                    HttpUtil.sendOkHttpRequest(url, new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {
                                            Toast.makeText(getContext(), "获取翻译数据失败！", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            final String result = response.body().string();
                                            Log.e("TranslateFragment", result);

                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    cv_result.setVisibility(View.VISIBLE);
                                                    JinshanParseUtil.parseJinshanChineseToEnglishJSONWithGson(result);
                                                    SharedPreferences pref = getActivity().getSharedPreferences("JinshanChineseToEnglishBaseMean", MODE_PRIVATE);

                                                    String queryText = pref.getString("queryText", "空");
                                                    String voiceText = pref.getString("voiceText", "空");
                                                    String voiceUrlText = pref.getString("voiceUrlText", "空");
                                                    String meanText = pref.getString("meanText", "空");
                                                    output.setText("");

                                                    if (!queryText.equals(content)) {
                                                        output.setText(content);
                                                        voiceUrl = null;
                                                    } else {
                                                        output.setText("");
                                                        voiceUrl = voiceUrlText;
                                                        output.setText(meanText);
                                                        QuereText = queryText;
                                                        MeanText = meanText;
                                                        VoiceTextUrl = voiceUrl;
                                                        VoiceText = voiceText;
                                                        List<Wordbook> wordbooks = DataSupport.findAll(Wordbook.class);
                                                        for (Wordbook wordbook : wordbooks) {
                                                            if (QuereText.equals(wordbook.getQuereText())) {
                                                                isCollect = true;
                                                                cb_collcet.setChecked(true);
                                                            } else {
                                                                isCollect = false;
                                                            }
                                                        }
                                                    }

                                                }
                                            });

                                        }
                                    });
                                    HttpUtil.sendOkHttpRequest(urlxml, new Callback() {
                                        @Override
                                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                            Toast.makeText(getActivity(), "获取翻译数据失败！", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                                            final String result = response.body().string();

                                            getActivity().runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String example = parseJinshanChineseToEnglishXMLWithPull(result);

                                                    if (!example.equals(null)) {
                                                        cv_example.setVisibility(View.VISIBLE);
                                                        tv_example.setText(example);
                                                    }

                                                }
                                            });

                                        }
                                    });

                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        IB_sound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (voiceUrl != null && voiceUrl != "空") {
                    try {
                        MediaPlayer mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(voiceUrl);
                        mediaPlayer.prepareAsync();
                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mediaPlayer) {
                                mediaPlayer.start();
                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getContext(), "暂无发音", Toast.LENGTH_SHORT).show();
                }
            }
        });
        IB_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!output.getText().toString().equals("")) {
                    final ClipboardManager clipboardManager = (ClipboardManager)
                            getActivity().getSystemService(Context.CLIPBOARD_SERVICE);

                    ClipData clipData = ClipData.newPlainText("Label", output.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);
                    Snackbar.make(view, "成功复制到剪切板", Snackbar.LENGTH_LONG).setAction("撤销", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ClipData clipData = ClipData.newPlainText("Label", "");
                            clipboardManager.setPrimaryClip(clipData);
                        }
                    }).show();
                }
            }
        });
        cb_collcet.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (MeanText != QuereText) {
                    if (isCollect == false) {
                        if (b) {
                            if(word!="--") {
                                isCollect = true;
                                Wordbook wordbook = new Wordbook();
                                wordbook.setQuereText(QuereText);
                                wordbook.setMeanText(MeanText);
                                wordbook.setVoiceText(VoiceText);
                                wordbook.setVoiceUrlText(VoiceTextUrl);
                                wordbook.save();
                                Toast.makeText(getContext(), "已收藏到单词本", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            isCollect = false;
                            DataSupport.deleteAll(Wordbook.class, "quereText = ?", QuereText);
                            Toast.makeText(getContext(), "已从单词本中移除", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        if (!b) {
                            isCollect = false;
                            DataSupport.deleteAll(Wordbook.class, "quereText = ?", QuereText);
                            Toast.makeText(getContext(), "已从单词本中移除", Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    if (b) {
                        isCollect = false;
                        Toast.makeText(getContext(), "翻译失败无法收藏", Toast.LENGTH_SHORT).show();
                        cb_collcet.setChecked(false);
                    }

                }
            }
        });
    }

    private void clearInputContent() {
        String content = input.getText().toString();
        if (!TextUtils.isEmpty(content)) {
            input.setText("");
        }
    }

}
